import 'dart:convert';

import 'package:cbec_app/components/app_conifg.dart';
import 'package:cbec_app/components/base/base_ctr.dart';
import 'package:cbec_app/components/http/network.dart';
import 'package:cbec_app/components/popup/password_check_popup.dart';
import 'package:cbec_app/components/popup/prepayment_card_popup.dart';
import 'package:cbec_app/components/popup/score_discount_popup.dart';
import 'package:cbec_app/routes/routes.dart';
import 'package:cbec_app/utils/EventMgr.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:cbec_app/utils/logger.dart';
import 'package:decimal/decimal.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';

///填写订单页控制器
class FillOrderController extends BaseController {
  ///下单参数 通过其他页面传入
  Map<String, dynamic> placeOrderParams = {};

  ///下单参数 选完优惠券/红包/积分/预付卡 重新刷新，计算价格，包含placeOrderParams的所有字段
  Map<String, dynamic> requestPlaceOrderParams = {};

  ///下单详情
  Map<String, dynamic> detail = {};

  ///商品列表
  List goodsList = [];

  ///地址信息
  Map<String, dynamic>? addressInfo = {};

  ///可用优惠券列表
  List couponList = [];

  ///优惠券优惠金额
  double useCouponPrice = 0;

  ///优惠券用于显示的金额
  String showCouponPrice = '';

  ///是否选择优惠券
  bool isSelectCoupon = false;

  ///已选优惠券id
  List useCouponIds = [];

  ///可用红包列表
  List redPackList = [];

  ///已选红包id
  List useRedPackIds = [];

  ///红包优惠金额
  double useRedPackPrice = 0;

  ///红包用于显示的金额
  String showRedPackPrice = '';

  ///实际支付价格
  String actualPrice = '';

  ///积分抵扣金额
  double pointsDiscountAmount = 0;

  var haveUsePoints = 0.0;

  ///积分用于显示的金额
  String showPointsPrice = '暂无可用';

  ///积分配置信息
  Map<String, dynamic> pointsInfo = {};

  ///预付卡配置信息
  Map<String, dynamic> payCardInfo = {};

  ///预付卡抵扣金额
  double cardDiscountAmount = 0;

  ///预付卡用于显示的金额
  String showCardPrice = '暂无可用';

  ///运费
  double priceExpress = 0;

  bool showTax = false;

  ///税费
  double tax = 0;

  ///订单备注
  String orderRemark = '';

  bool isDepositAgree = false;

  // 整单优惠金额
  double priceFullDiscount = 0;

  // 活动优惠
  double activityDiscount = 0;

  // 商品促销
  double priceGoodsDiscount = 0;

  int commodityForm = 0;

  bool isFirst = false;

  String deposit = '';

  bool hasBonded = false;

  @override
  void onInit() async {
    super.onInit();
    isFirst = true;
    placeOrderParams = Get.arguments;
    logger.d('请求参数 === $placeOrderParams');
    requestPlaceOrderParams.addAll(placeOrderParams);
    await prePlaceOrder();
    await getCanUsedPoints();
    await getCanUsePayCard();
    update();
    EventMgr.on(EventType.selectAddress, (data) {
      print('看看选中的地址是 ==== $data');
      placeOrderParams['addressId'] = data['id'];
      addressInfo = data;
      // 更换地址，从新刷新
      isFirst = true;
      requestPlaceOrderParams.addAll(placeOrderParams);
      prePlaceOrder();
      getCanUsedPoints();
      getCanUsePayCard();

      update();
    });
  }

  ///准备下单页面数据
  Future prePlaceOrder() async {
    Tools.showLoading();
    return Network.prePlaceOrder(requestPlaceOrderParams).then((value) {
      Tools.hideLoading();
      detail = value;
      hasBonded = value['hasBonded'];
      print('hasBonded ==== $hasBonded');
      if (isFirst) {
        deposit = value['pricePay'].toString();
        isFirst = false;
      }
      goodsList = value['goodsList'] ?? [];
      if (goodsList.isNotEmpty) {
        commodityForm = goodsList.first['commodityForm'];
      }
      addressInfo = value['addressInfo'];
      couponList = value['couponList'] ?? [];
      redPackList = value['redDnvelopeList'] ?? [];
      if (value['priceCoupon'] > 0) {
        showCouponPrice = '-￥${value['priceCoupon']}';
      } else {
        showCouponPrice = couponList.isNotEmpty ? '请选择' : '暂无可用';
      }
      if (value['priceRedPacket'] > 0) {
        showRedPackPrice = '-￥${value['priceRedPacket']}';
      } else {
        showRedPackPrice = redPackList.isNotEmpty ? '请选择' : '暂无可用';
      }
      actualPrice = value['pricePay'].toString();
      priceExpress = double.parse(value['priceExpress'].toString());
      showTax = value['showTax'];
      tax = double.parse(value['tax'].toString());
      priceGoodsDiscount = value['priceGoodsDiscount'];
      calculateActivityDiscount();
      update();
    }).catchError((onError) async {
      // await Future.delayed(const Duration(seconds: 1));
      Tools.hideLoading();
      Get.back();
      Tools.showToast(onError);
    });
  }

  ///获取积分和预付卡商品列表参数
  List<Map<String, dynamic>> getPointsCardParams({bool isContainPoints = true}) {
    List<Map<String, dynamic>> arr = [];
    Map<String, dynamic> info = {};
    for (var item in goodsList) {
      info['buyNum'] = item['buyNum'];
      info['commodityType'] = item['commodityType'];
      info['goodsId'] = item['goodsId'];
      info['price'] = item['price'];
      info['priceActual'] = item['priceActual'];
      info['priceExpress'] = item['priceExpress'];
      Decimal pointsDiscountAmountDecimal = Decimal.parse(pointsDiscountAmount.toStringAsFixed(2));
      Decimal pricePayDecimal = Decimal.parse(detail['pricePay'].toStringAsFixed(2));
      print('isContainPoints ===== $isContainPoints');
      info['pricePay'] = isContainPoints ? pricePayDecimal : pricePayDecimal + pointsDiscountAmountDecimal;
      info['priceTax'] = item['priceTax'];
      info['priceTotal'] = item['priceTotal'];
      info['totalNum'] = item['totalNum'];
      arr.add(info);
    }
    return arr;
  }

  ///获取可用积分
  Future getCanUsedPoints() {
    Tools.showLoading();
    Map<String, dynamic> params = {};
    pointsDiscountAmount = 0;
    params['goodsList'] = goodsList;
    // getPointsCardParams();
    //预售订单
    if (detail['presaleType'] != null) {
      params['money'] = detail['pricePay'];
    }
    params['type'] = getPayType();
    return Network.getCanUsePoints(params).then((value) {
      Tools.hideLoading();
      pointsInfo = value;
      showPointsPrice = (pointsInfo.isNotEmpty && pointsInfo['maxUsePoints'] > 0) ? '请选择' : '暂无可用';
      update();
    }).catchError((onError) {
      Tools.hideLoading();
    });
  }

  ///获取订单付款类型
  int getPayType() {
    switch (detail['presaleType']) {
      case 2: //定金预售
        return 1;

      case 1: //全款预售
      case null: //非预售订单
      default:
        return 0;
    }
  }

  ///选择积分支付
  void selectPointsPay() async {
    await getCanUsedPoints();
    showScoreDiscountPopup(
      info: pointsInfo,
      onConfirm: (discountAmount) {
        usePointsDiscount(discountAmount);
      },
    );
  }

  ///获取可用预付卡
  Future getCanUsePayCard() {
    Tools.showLoading();
    Map<String, dynamic> params = {};
    cardDiscountAmount = 0;
    params['goodsList'] = goodsList;
    // getPointsCardParams(isContainPoints: false);
    //预售订单
    if (detail['presaleType'] != null) {
      params['money'] = detail['pricePay'];
    }
    params['type'] = getPayType();
    if (pointsInfo['pointsRadio'] == null) {
      Decimal pointsDiscountAmountDecimal = Decimal.parse(pointsDiscountAmount.toStringAsFixed(2));
      params['points'] = pointsDiscountAmountDecimal;
    } else {
      int pointsRadio = pointsInfo['pointsRadio'];
      Decimal pointsDiscountAmountDecimal = Decimal.parse(pointsDiscountAmount.toStringAsFixed(2));
      Decimal pointsRadioDecimal = Decimal.fromInt(pointsRadio);
      Decimal result = pointsDiscountAmountDecimal * pointsRadioDecimal;
      params['points'] = result;
    }

    return Network.getCanUsePayCard(params).then((value) {
      Tools.hideLoading();
      payCardInfo = value;
      showCardPrice = (payCardInfo.isNotEmpty && payCardInfo['maxUseBdPayCardBalance'] > 0) ? '请选择' : '暂无可用';
      update();
    }).catchError((onError) {
      Tools.hideLoading();
    });
  }

  ///选择预付卡支付
  void selectCardPay() async {
    await getCanUsePayCard();
    showPrepaymentCardPopup(
      info: payCardInfo,
      onConfirm: (discountAmount) {
        useCardDiscount(discountAmount);
      },
    );
  }

  ///输入订单备注
  void inputRemark(String value) {
    orderRemark = value;
  }

  bool isUseCoupon() {
    if (couponList.isEmpty) {
      return false;
    } else {
      if (useCouponIds.isEmpty) {
        return true;
      } else {
        return false;
      }
    }
  }

  /// 判断是否使用了红包
  bool isUseRedPack() {
    if (redPackList.isEmpty) {
      return false;
    } else {
      if (useRedPackIds.isEmpty) {
        return true;
      } else {
        return false;
      }
    }
  }

  ///下单
  void placeOrder() {
    if (placeOrderParams['type'] == 5) {
      if ((detail['presalePayReturn'] == 0)) {
        if (isDepositAgree == false) {
          Tools.showToast('请同意预售协议');
          return;
        }
      }
    }
    if (addressInfo == null) {
      Tools.showToast('请选择收货地址');
      return;
    }
    if ((isUseCoupon() || isUseRedPack())) {
      Tools.showModal(
        content: '当前有可使用的优惠券或红包，确定提交订单吗?',
        onConfirm: (tag) {
          SmartDialog.dismiss(tag: tag);
          usePointsCardPay();
        },
      );
    } else {
      usePointsCardPay();
    }
  }

  ///使用了积分或预付卡支付
  void usePointsCardPay() {
    if (pointsDiscountAmount != 0 || cardDiscountAmount != 0) {
      checkPayPassword();
    } else {
      submitOrder();
    }
  }

  ///验证支付密码
  void checkPayPassword() async {
    bool hasPassword = await Network.hasPayPassword();
    // bool hasPassword = true;
    if (hasPassword) {
      showPasswordCheckPopup(((success) {
        //这里返回的success就是是否验证成功，如果success为true就是密码通过，false就是密码不通过
        if (success) {
          submitOrder();
        } else {
          Tools.showToast('密码错误，请重新输入');
        }
      }));
    } else {
      submitOrder();
    }
  }

  ///提交订单
  void submitOrder() async {
    var activityId = placeOrderParams['activityId'];
    var addressId = addressInfo?['id'];
    var bookId = detail['bookId'];
    var bookNum = placeOrderParams['bookNum'];
    var client = GetPlatform.isIOS ? AppConfig.clientIos : AppConfig.clientAndroid;
    var couponIds = useCouponIds.where((element) => element != null).toList();
    var tempGoodsList = goodsList.map((item) {
      Map info = {"buyNum": item['buyNum'], "goodsId": item['goodsId'], "isConvenient": item['isConvenient'], "isRaffleGoods": item['isRaffleGoods'], "isSend": item['isSend'], "specNum": item['specNum']};
      return info;
    }).toList();
    var haggleId = '';
    var isCart = 0;
    var payWayCode = '';
    var points = haveUsePoints;

    print('points === $points');

    var pointsMoney = pointsDiscountAmount;

    var preMoney = cardDiscountAmount;
    var redPacket = useRedPackPrice;
    var redPacketId = useRedPackIds.where((element) => element != null).toList();
    var shippingType = 0;
    var sid = placeOrderParams['sid'];
    var type = placeOrderParams['type'];
    var userMessage = orderRemark;

    var requestParams = {
      "activityId": activityId,
      "addressId": addressId,
      "bookId": bookId,
      "bookNum": bookNum,
      "client": client,
      "couponIds": couponIds,
      "goodsList": tempGoodsList,
      "haggleId": haggleId,
      "isCart": isCart,
      "payWayCode": payWayCode,
      "points": points,
      "pointsMoney": pointsMoney,
      "preMoney": preMoney,
      "redPacket": redPacket,
      "redPacketId": redPacketId,
      "shippingType": shippingType,
      "sid": sid,
      "type": type,
      "userMessage": userMessage,
    };

    logger.i('提交订单参数${requestParams.toString()}');

    Tools.showLoading();
    Network.placeOrder(requestParams).then((value) {
      Tools.hideLoading();
      print(' 提交订单 response $value');

      var priceOrder = value['priceOrder'];
      if (priceOrder > 0) {
        Get.toNamed('${Routes.cashier}/?sn=${value['paySn']}&price=$actualPrice', arguments: {'hasBonded': hasBonded});
      } else {
        Get.toNamed('${Routes.paySuccess}/?price=$priceOrder&paySelected=0');
      }
    }).catchError((onError) {
      Tools.hideLoading();
    });
  }

  ///确定使用优惠券
  void useCoupon(List ids, String price) {
    useCouponIds = ids;

    pointsDiscountAmount = 0;
    haveUsePoints = 0.0;
    cardDiscountAmount = 0;

    useCouponPrice = double.parse(price);
    // TODO 重新赋值算价
    requestPlaceOrderParams.addAll(placeOrderParams);
    requestPlaceOrderParams['couponIds'] = useCouponIds;
    requestPlaceOrderParams['points'] = haveUsePoints;
    requestPlaceOrderParams['pointsMoney'] = pointsDiscountAmount;
    requestPlaceOrderParams['preMoney'] = cardDiscountAmount;

    prePlaceOrder();
    getCanUsedPoints();
    getCanUsePayCard();
  }

  ///确定使用红包
  void useRedPack(String id, String price) {
    if (id.isEmpty) {
      useRedPackIds = [];
    } else {
      useRedPackIds = id.split(',');
    }
    useRedPackPrice = double.parse(price);
    pointsDiscountAmount = 0;
    haveUsePoints = 0.0;
    cardDiscountAmount = 0;

    // TODO 重新赋值算价
    requestPlaceOrderParams.addAll(placeOrderParams);
    requestPlaceOrderParams['couponIds'] = useCouponIds;
    requestPlaceOrderParams['points'] = haveUsePoints;
    requestPlaceOrderParams['pointsMoney'] = pointsDiscountAmount;
    requestPlaceOrderParams['preMoney'] = cardDiscountAmount;

    requestPlaceOrderParams.addAll(placeOrderParams);
    if (id.isNotEmpty) {
      requestPlaceOrderParams['redPacket'] = useRedPackIds.length;
      requestPlaceOrderParams['redPacketId'] = useRedPackIds;
    } else {
      if (requestPlaceOrderParams.containsKey('redPacket')) {
        requestPlaceOrderParams.remove('redPacket');
      }
      if (requestPlaceOrderParams.containsKey('redPacketId')) {
        requestPlaceOrderParams.remove('redPacketId');
      }
    }
    prePlaceOrder();
    getCanUsedPoints();
    getCanUsePayCard();
  }

  ///确定使用积分抵扣
  void usePointsDiscount(String discountAmount) {
    cardDiscountAmount = 0;
    showCardPrice = '请选择';
    //print('showCardPrice ==== $showCardPrice');
    pointsDiscountAmount = double.parse(discountAmount);
    if (pointsDiscountAmount > 0) {
      showPointsPrice = '-￥$discountAmount';
    } else {
      showPointsPrice = '-￥0';
      haveUsePoints = 0.0;
    }

    haveUsePoints = double.parse(discountAmount) * pointsInfo['pointsRadio'];
    // TODO 重新赋值算价
    requestPlaceOrderParams.addAll(placeOrderParams);
    requestPlaceOrderParams['points'] = haveUsePoints;
    requestPlaceOrderParams['pointsMoney'] = pointsDiscountAmount;
    if (requestPlaceOrderParams.containsKey('preMoney')) {
      requestPlaceOrderParams.remove('preMoney');
    }
    prePlaceOrder();
  }

  ///确定使用预付卡抵扣
  void useCardDiscount(String discountAmount) {
    // TODO 重新赋值算价
    cardDiscountAmount = double.parse(discountAmount);

    if (cardDiscountAmount > 0) {
      showCardPrice = '-￥$discountAmount';
    } else {
      showCardPrice = '-￥0';
    }

    requestPlaceOrderParams.addAll(placeOrderParams);
    Decimal cardDiscountAmountDecimal = Decimal.parse(cardDiscountAmount.toStringAsFixed(2));
    requestPlaceOrderParams['preMoney'] = cardDiscountAmountDecimal;
    prePlaceOrder();
  }

  void calculateActivityDiscount() {
    if (detail['priceSpecialDiscount'] > 0) {
      activityDiscount = detail['priceSpecialDiscount'];
    } else if (detail['priceOrderActivityDiscount'] > 0) {
      activityDiscount = detail['priceOrderActivityDiscount'];
    } else if (detail['priceNewUserDiscount'] > 0) {
      activityDiscount = detail['priceNewUserDiscount'];
    }

    /*

    // 活动类型
    int type = placeOrderParams['type'];

    switch (type) {
      case 0:
        break;
      case 2:
        activityDiscount = detail['priceSpecialDiscount'];
        break;
      case 3:
        activityDiscount = detail['priceOrderActivityDiscount'];
        break;
      case 4:
        activityDiscount = detail['priceOrderActivityDiscount'];
        break;
      case 5:
        activityDiscount = detail['priceOrderActivityDiscount'];
        break;
      case 6:
        break;
      case 7:
        break;
      case 8:
        activityDiscount = detail['priceOrderActivityDiscount'];
        break;
      case 9:
        activityDiscount = detail['priceNewUserDiscount'];
        print('activityDiscount ====== $activityDiscount');

        break;
      default:
    }
     */
  }

  @override
  void onClose() {
    super.onClose();
    EventMgr.off(EventType.selectAddress);
  }

  void changeProtocol(bool selected) {
    isDepositAgree = selected;
    update();
  }
}
